<?php
namespace Home\Controller;
use Think\Controller;
class AlipayController extends CommonController {
	
	public function _initialize() {
		parent::_initialize();
		Vendor('Alipay.Corefunction');
		Vendor('Alipay.Rsafunction');
        Vendor('Alipay.Md5function');
        Vendor('Alipay.Notify');
        Vendor('Alipay.Submit');
	} 
	
    public function index(){
		$this->checkLoginRedirect();
		$flowId = I('flowId','');
		$onlinePayFlowSrv = D('OnlinePayFlow');
		$flowInfo = $onlinePayFlowSrv->getOne($flowId);
		if(empty($flowInfo) || $flowInfo['status']!=0){//回订单中心
			redirect('/Home/Account/orderCenter/', 0, '');
		}
		$userSrv = D('User');
		$userInfo = $userSrv->getUserInfo($this->uId());
		$buyer_account_no = $this->uId();
		$buyer_reg_date = $userInfo['insert_time'];
		$alipay_config = C('ALIPAY_CONFIG');
		$total_fee = num_f($flowInfo['should_pay']);
		$out_trade_no = $flowId;
		/****************调用风险检测接口 开始*****************/
		$para['timestamp'] =  date("Y-m-d H:i:s");
		$para['_input_charset'] = $alipay_config['input_charset'];
		$para['buyer_account_no'] = $buyer_account_no;
		$para['buyer_reg_date'] = $buyer_reg_date;
		$para['order_amount'] = $total_fee;
		$para['order_category'] = $alipay_config['order_category'];
		$para['order_credate_time'] = date("Y-m-d H:i:s");
		$para['order_item_name'] = $alipay_config['subject'];
		$para['order_no'] =  $out_trade_no;
		$para['partner'] =  $alipay_config['partner'];
		$para['payment_type'] =  $alipay_config['payment_type'];
		$para['scene_code'] =  $alipay_config['scene_code'];
		$para['seller_email'] =  $alipay_config['seller_email'];
		$para['service'] =  "alipay.security.risk.detect";
		$para['terminal_type'] = $alipay_config['terminal_type'];
		$alipaySubmit = new \AlipaySubmit($alipay_config);
		$para = $alipaySubmit->buildRequestPara($para);
		$para = createLinkstringUrlencode($para);
		$url = C('ALIPAY_API') ."?".$para;
		$res = httpResponseGET($url);
		/***************调用风险检测接口 结束****************/
		
		$format = "xml";
		$v = "2.0";
		$req_id = date('Ymdhis');
		$notify_url = $alipay_config['notify_url'];
		$call_back_url = $alipay_config['call_back_url'];
		$merchant_url = $alipay_config['merchant_url'];
		$seller_email = $alipay_config['seller_email'];
		// $out_trade_no = $_POST['out_trade_no'];
		$subject = $alipay_config['subject'];
		// $total_fee = $total_fee;
		$pay_expire = $alipay_config['pay_expire'];
		
		$req_data = '<direct_trade_create_req><notify_url>' . $notify_url . '</notify_url><call_back_url>' . $call_back_url . '</call_back_url><seller_account_name>' . $seller_email . '</seller_account_name><out_trade_no>' . $out_trade_no . '</out_trade_no><subject>' . $subject . '</subject><total_fee>' . $total_fee . '</total_fee><merchant_url>' . $merchant_url . '</merchant_url><pay_expire>' . $pay_expire . '</pay_expire></direct_trade_create_req>';

		$para_token = array(
				"service" => "alipay.wap.trade.create.direct",
				"partner" => trim($alipay_config['partner']),
				"sec_id" => trim($alipay_config['sign_type']),
				"format"	=> $format,
				"v"	=> $v,
				"req_id"	=> $req_id,
				"req_data"	=> $req_data,
				"_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
		);

		$alipaySubmit = new \AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestHttp($para_token);

		$html_text = urldecode($html_text);

		$para_html_text = $alipaySubmit->parseResponse($html_text);

		$request_token = $para_html_text['request_token'];

		$req_data = '<auth_and_execute_req><request_token>' . $request_token . '</request_token></auth_and_execute_req>';

		$parameter = array(
				"service" => "alipay.wap.auth.authAndExecute",
				"partner" => trim($alipay_config['partner']),
				"sec_id" => trim($alipay_config['sign_type']),
				"format"	=> $format,
				"v"	=> $v,
				"req_id"	=> $req_id,
				"req_data"	=> $req_data,
				"_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
		);
		$alipaySubmit = new \AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($parameter, 'get', '确认');
		
		$html_all = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>支付宝即时到账交易接口接口</title></head>'.$html_text.'</body></html>';
		
		$this->show($html_all);
    }
	
	public function notifyUrl(){
		$alipay_config = C('ALIPAY_CONFIG');
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();

		if($verify_result) {//验证成功
			sys_pay_log("************************alipay_notify start*****************************");
			$notify_data = $alipayNotify->decrypt(I('notify_data'));
			sys_pay_log("notify_data => " .json_encode($notify_data));
			$doc = new DOMDocument();
			$doc->loadXML($notify_data);
			sys_pay_log("tag_notify => " .$doc->getElementsByTagName( "notify" )->item(0)->nodeValue);
			
			if( ! empty($doc->getElementsByTagName( "notify" )->item(0)->nodeValue) ) {
				//商户订单号
				$out_trade_no = $doc->getElementsByTagName( "out_trade_no" )->item(0)->nodeValue;
				//支付宝交易号
				$trade_no = $doc->getElementsByTagName( "trade_no" )->item(0)->nodeValue;
				//交易状态
				$trade_status = $doc->getElementsByTagName( "trade_status" )->item(0)->nodeValue;
				
				if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {	
					$paySrv = D('Pay');
					$paySrv->completeOnlinePayFlow($out_trade_no,C('ALIPAY_PREFIX') .$trade_no,C('PAYMENT_TYPE.ALIPAY'));
				}
				echo "success";
			}
			sys_pay_log("************************alipay_notify end*****************************");
		} else {
			echo "fail";
		}
	}
	
	public function callBackUrl(){
		$alipay_config = C('ALIPAY_CONFIG');
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyReturn();
		if($verify_result) {//验证成功

			//商户订单号
			$out_trade_no = I('out_trade_no');

			//支付宝交易号
			$trade_no = I('trade_no');

			//交易状态
			$result = I('result');

			$paySrv = D('Pay');
			$res_com = $paySrv->completeOnlinePayFlow($out_trade_no,C('ALIPAY_PREFIX') .$trade_no,C('PAYMENT_TYPE.ALIPAY'));
			redirect("/Home/Account/orderCenter",0,"");
			echo "验证成功<br />";

		}else {

			echo "验证失败";
		}
	}
}